# -*-coding:utf-8 -*-
# @Time: 2023/2/21 0021 下午 14:00
# @Author: Cwoner
# @Organization: CTIM
# @Software: PyCharm
import requests
import os
import json
import time

if not os.path.isdir('logs'):
    os.mkdir('logs')

HOST = 'http://39.99.140.242'


def log(info):
    print(info)
    try:
        with open('./logs/error.log', 'a+', encoding='utf-8') as f:
            f.write(info)
    except:
        return

def upload_file(data,content,c=0):
    # data = {
    #     'entity_id':entity_id,
    #     'title':title,
    #     'tid':tid,
    #     'file_name':file_name,
    #     'origin_url':origin_url,
    #     'ndate':ndate
    # }
    headers = {'sign':'9ab8f5469811bebc75543ab4af32f724'}
    try:
        res = requests.post(f'{HOST}/newspaper/api/update_data/', files={'file': ('FILE', content, 'image/jpg')},data=data,headers=headers)
    except:
        time.sleep(2)
        if c > 3:
            info = f'上传出错：{json.dumps(data, ensure_ascii=False)}\n'
            log(info)
            return
        return upload_file(data,content,c+1)
    if res.status_code == 200:
        data = res.json()
        code = data['code']
        if code == 200:
            return
        elif code == 199:
            info = f'上传异常：{json.dumps(data, ensure_ascii=False)}已存在。\n'
            log(info)
            return
        elif code == 199:
            info = f'上传异常：{json.dumps(data, ensure_ascii=False)}已存在。\n'
            log(info)
            return
        else:
            info = f'上传出错：{json.dumps(data,ensure_ascii=False)}，媒体不存在。\n'
            log(info)
    else:
        if c > 3:
            info = f'上传出错：{json.dumps(data, ensure_ascii=False)},响应状态码:{res.status_code}。\n'
            log(info)
            return
        return upload_file(data,content,c+1)